import React from 'react';
import { Row, Col, Cascader, Input, Button, Table, Card, Select, Pagination, Modal, message, Icon, Tooltip  } from 'antd';
import { getServicePeople, deleteServiceStaff, selectElderlyInfo, exportService } from '../../services/api';
import { connect } from 'dva';
import PersonModal from './indexModal';
import { formatCascader } from '../../common/common'
import './index.css';
import {fileDownLoad} from '../../config/index';

const confirm = Modal.confirm;
const Option = Select.Option;

class Personal extends React.Component {
	componentDidMount() {
		this.getServicePeople();
		this.props.dispatch({type: 'example/setAreaInfo', res: !this.props.areaInfo })
		this.props.dispatch({type: 'example/setServiceType', res: !this.props.serviceType })
		this.props.dispatch({type: 'example/setServicePersons', res: !this.props.servicePersons })
	}
	
	state = {
		//表格数据
		dataSource: [],
		//数据总条数
		total: 10,
		//当前页数
		pageCurrent: 1,
		//当前条数
		pageSize: 10,
		//查询所需要的条件
		fStreetCommunity: [],
		fName: '',
		fPhone: '',
		area:'',
		content:'',
		//区域树结构
		deptTree:[],
		//服务类型列表
		serviceTypeList:[],
		//修改数据ID
		serviceStaffId: "",
		//操作类型
		optionType: "",
		historyList: [],

		dataInfo:'', //文件导出路径

		loading:false,
		selectedRowKeys:[]
	};

	columns = [{
		title: '街办区域',
		className: 'columnTitle',
		dataIndex: 'fStreetCommunity'
	}, {
		title: '服务人员',
		className: 'columnTitle',
		dataIndex: 'fName'
	}, {
		title: '电话',
		className: 'columnTitle',
		dataIndex: 'fPhone'
	},{
		title: '服务内容',
		className: 'columnTitle',
		dataIndex: 'fContent'
	},{
		title: '服务次数',
		className: 'columnTitle',
		dataIndex: 'fCount',
		render:(val) => val === '0' ? '--' : `${val}次`,
	}, {
		title: '操作',
		className: 'columnTitle',
		key: 'desc',
		width: 100,
		render: (text, record) => (  
		<span>
			<Tooltip title="修改">
			<Icon type="form" onClick={() => this.updataServiceStaff(record, true)} className='tableBtn'/>
			</Tooltip>
			<Tooltip title="查看">
			<Icon type="bars" onClick={() => this.detailServiceStaff(record)} className='tableBtn'/>
			</Tooltip>
			<Tooltip title="历史记录">
			<Icon type="dot-chart" onClick={() => this.updataServiceStaff(record, false)} className='tableBtn'/>
			</Tooltip>
			</span> 
	)
	}];
	/** 
	 * 获取人员列表
	*/
	getServicePeople = async() => {
		this.setState({loading:true})
		let param = {
			fName: this.state.fName,
			fPhone: this.state.fPhone,
			fStreetCommunity: this.state.area ? this.state.area[this.state.area.length - 1]:'',
			fServiceType:this.state.content,
			pageCurrent: this.state.pageCurrent,
			pageSize: this.state.pageSize
		};
		const res = await getServicePeople(param);
		if(res.code === 200) {
			this.setState({
				dataSource: res.data.dataList,
				total: res.data.totalNumber,
				loading:false
			})
		} else {
			this.setState({loading:false})
			res.msg && message.error (res.msg)
		}
	}
	/** 
	 * 查询历史记录
	*/
	getHistory = async (params) => {
		let param = params ? params : {
			fServiceStaffId: this.state.serviceStaffId
		};
		let res = await selectElderlyInfo(param);
		if(res.code === 200) {
			this.setState({historyList: res.data})
			return;
		}
		this.setState({historyList: []})
	}
	/** 
	 * 表格数据选中
	*/
	checkedChange = (selectedRowKeys, selectedRows) => {
		this.setState({
			selectionData: selectedRows,
			selectedRowKeys:selectedRowKeys
		});
	}

	
	//导出服务数据
	async exportService(){
		let param = {
			fName: this.state.fName,
			fPhone: this.state.fPhone,
			fStreetCommunity: this.state.area ? this.state.area[this.state.area.length - 1]:'',
			fServiceType:this.state.content,
			fstaffId:'',
			pageCurrent: 0,
			pageSize: 0
		}
		const response = await exportService(param);
		if(response.code === 200){
          this.setState({
			dataInfo:response.data,
		  },()=>{
			fileDownLoad(this.state.dataInfo,'服务老人表','xls');	
			message.info('信息导出成功')
		  })
		} else {
		  response.msg && message.error(response.msg)
		}
	}

	/** 
	 * 获取姓名
	*/
	getName = (e) => {
		this.setState({
			fName: e.target.value
		});
	}
	/** 
	 * 获取电话
	*/
	getPhone = (e) => {
		this.setState({
			fPhone: e.target.value
		});
	}
	/** 
	 * 查询
	*/
	search = () => {
		this.getServicePeople();
	}
	/** 
	 * 删除
	*/
	delete = () => {
		let that = this;
		let len = this.state.selectionData ? this.state.selectionData.length : 0;
		if(len <= 0) {
			message.warning('请至少选择一条您要进行操作的数据');
			return;
		}
		let fIdLIst = [];
		for(let data of this.state.selectionData){
			fIdLIst.push(data.fId)
		}
		confirm({
			title: '是否确定删除已勾选数据?',
			content: `已选择 ${len} 条数据，删除后将无法追回`,
			okText: '确认',
    		cancelText: '取消',
			onOk() {
				that.deleteServiceStaff(fIdLIst);
			},
			onCancel() {

			},
		});
	}

	async deleteServiceStaff (param) {
		let res = await deleteServiceStaff(param);
		if(res.code === 200){
			this.getServicePeople();
			this.setState({
				selectionData:[]
			})
			message.success('删除成功')
		}else {
			message.error(res.msg);
		}
	}


	/** 
	 * 改变当前页数
	*/
	currentChange = (page, pageSize) => {
		this.setState({
			pageCurrent: page
		}, ()=>{
			this.getServicePeople();
		});
	}
	/** 
	 * 改变当前条数
	*/
	sizeChange = (current, size) => {
		this.setState({
			pageSize: size
		}, ()=>{
			this.getServicePeople();
		});
	}

	/**
	 * 添加服务人员按钮
	 */
	addServiceStaff = () => {
		this.setState({serviceStaffId: "", optionType: "insert"})
		this.operateModal();
	}

	/**
	 * 修改服务人员按钮
	 */
	async updataServiceStaff (record, status) {
		await this.setState({serviceStaffId: record.fId, optionType: status ? "update" : 'history'});
		if(!status) {
			await this.getHistory();
		}
		this.operateModal();
	}

	/**
	 * 服务人员详情按钮
	 */
	detailServiceStaff (record) {
		this.setState({serviceStaffId: record.fId, optionType: "detail"})
		this.operateModal();
	}

	/** 
	 * 模态框操作
	*/
	operateModal = () => {
		this.props.dispatch({type: 'example/setPersonalModal', res: !this.props.personalModal});
	}

	 /**
     * 级联选择器
     * @param {*} value 
     */
   
	
	/**
	 * 更改服务类型
	 * @param {*} value 
	 */

	render() {
		const rowSelection = {
			onChange: this.checkedChange
		};
		return (
			<div style={{padding: '20px 40px'}}>
				<Card>
				<div style={{display: 'flex'}}>
					<Row  className='searchDiv searchCard' type="flex" justify="space-around">
						<Col span={5} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>街办区域:</span>
							</Row>
							<Row>
								<Cascader style={{width: '100%'}} options={formatCascader(this.props.areaInfo, 'fId', 'fName', 'children')} onChange={(val)=>{this.setState({area:val})}} changeOnSelect placeholder="请选择..."/>
							</Row>
						</Col>
						<Col span={5} className='searchDivChildren'>
							<Row  style={{marginBottom: 10}}>
								<span className='titleSpan'>服务人员姓名:</span>
							</Row>
							<Row>
								<Input onChange={this.getName} placeholder="请输入..." />
							</Row>
						</Col>
						<Col span={5} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务人员电话:</span>
							</Row>
							<Row>
								<Input onChange={this.getPhone} placeholder="请输入..." />
							</Row>
						</Col>
						<Col span={5} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务内容:</span>
							</Row>
							<Row>
								<Select onChange={(value)=>{this.setState({content:value})}} placeholder="请选择..." style={{ width: '100%' }} allowClear>
								{
									this.props.serviceType.map( (item) => (<Option value={item.fId} key={item.fId}>
										{
											item.fName
										}
										</Option>))
								}
								</Select>
							</Row>
						</Col>
					</Row>
					<div style={{height: 67,lineHeight: '100px'}}>
					<Button type="primary" onClick={this.search}>查询</Button>
					</div>
				</div>
				</Card>
				
				<div className="search">
				  <Button  type="primary"  onClick={()=>this.addServiceStaff()} >新增</Button>
				  <Button type="danger"  onClick={()=>this.delete()} >删除</Button>
				  <Button onClick={()=>this.exportService()} style={{background:'#bb9ffa',color:'white'}}>导出</Button>
				</div>
				<Card>
					<Table
					    // size='small'
						rowSelection={rowSelection}
						rowKey={record => record.fId}
						style={{marginBottom: 20}}
						columns={this.columns}
						dataSource={this.state.dataSource}
						pagination={false}
						locale={{
							emptyText: '暂无数据'
						}}
						loading={this.state.loading}
					/>
					<Pagination size="small" total={this.state.total} showSizeChanger showQuickJumper showTotal={(total)=>(<span>共{total}条</span>)} onChange={this.currentChange} onShowSizeChange={this.sizeChange}/>
				</Card>
				<PersonModal visable={this.props.personalModal} operateModal={this.operateModal} query={this.getHistory} data={this.state.serviceStaffId} getServicePeople={this.getServicePeople} optionType={this.state.optionType} historyList={this.state.historyList}/>
			</div>
		)
	}
}

export default connect((state)=>({
	personalModal: state.example.personalModal,
	areaInfo: state.example.areaInfo,
	serviceType: state.example.serviceType,
	servicePersons: state.example.servicePersons,
  }))(Personal)